package com.liudadan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        InputStream inputStream = null;

        try {
            String mybatisConfigFilePath = "config/mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(mybatisConfigFilePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        sqlSessionFactory  = new SqlSessionFactoryBuilder().build(inputStream);
    }
    //工具类 -> 建议使用static
    //方法 ->  sqlSession
    //不开启自动提交 DQL

    public static SqlSession openSession(){
        return sqlSessionFactory.openSession();
    }
    //开启自动提交 DML
    public static SqlSession oepnAutoCommitSession(){
        return sqlSessionFactory.openSession(true);
    }
}
